<?php
//自动生成,请根据需要修改
namespace app\login\controller;
use app\common\controller\Base;
use function MongoDB\BSON\toJSON;
use phpDocumentor\Reflection\Types\Object_;
use think\Db;
use EasyWeChat\Factory;
use think\Exception;
use think\Validate;
use tools\curl\Curl;

/**
 * @title 登录页面（模块04-02）
 * @description 登录说明
 * @group 登录
 * @header name:model_id require:0 default:02-02 desc:模块
 * @groupremark 已使用错误码：1-04-02-0001 校验失败 1-04-02-0002 添加失败 1-04-02-0003 编辑校验失败 1-04-02-0004 编辑失败 1-04-02-0005 获取详情失败  1-04-02-0006 获取列表失败 1-04-02-0007获取单个详情失败 1-04-02-0008 删除失败
 */
class Login extends Base
{
    /**
     * @title 后台管理员登录
     * @description 后台管理员登录
     * @author 宋晓文
     * @url /login/login/admin_login
     * @method POST
     * @param name:username type:int require:1 default:1 other: desc:账号
     * @param name:password type:int require:1 default:1 other: desc:密码
     * @return data:帐号信息@!
     * @data token:token
     *
     */
    public function admin_login()
    {
        $data = input();
        //验证器
        $validate = new Validate([
            'username' => 'require',
            'password' => 'require',
        ], [
            'username' => '账号不能为空',
            'password' => '密码不能为空',
        ]);
        if (!$validate->check($data)) {
            $msg['msg'] = $validate->getError();
            return $this->errorJson($msg);
        }
        //获取账号信息
        $account = Db::name('account')->where('account_name',$data['username'])->find();
        //判断账号和密码是否正确
        if(!$account || $account['password']!==md5($data['password'])){
            $msg['msg'] = '账号或密码不正确';
            return $this->errorJson($msg);
        }
        //接口 - 获取用户数据
        $user_model_api = Config('model_api.user');
        $url = $user_model_api . "/admin_user/info";
        $admin_user = Curl::get($url, array('account_id' => $account['id']));
        $msg['admin_user'] = $admin_user;
        $admin_user_status = Curl::json2arr($admin_user)['status'];
        //判断账号是否存在
        if (!$admin_user_status) {
            $msg['msg'] = '该账号无管理员权限';
            return $this->errorJson($msg);
        }
        //取data重新赋值
        $admin_user = Curl::json2arr($admin_user)['data'];
        //判断是否被禁用
        if ($admin_user['status'] == 0) {
            $msg['msg'] = '该账号管理员已被禁用';
            return $this->errorJson($msg);
        }

        //生成并保存token
        $token_str = save_token($account['id']);
        //登录成功
        $msg['msg'] = '登录成功';
        $msg['token'] = $token_str;
        return $this->successJson($msg);
    }

    /**
     * @title 商家后台登录
     * @description 商家后台登录
     * @author 肖思哲
     * @author 修改：宋晓文 2019/4/22
     * @url /login/login/merchant_login
     * @method POST
     * @param name:username type:int require:1 default:1 other: desc:账号
     * @param name:password type:int require:1 default:1 other: desc:密码
     * @return data:帐号信息@!
     * @data token:token
     *
     */
    public function merchant_login()
    {
        $data = input();
        //验证器
        $validate = new Validate([
            'username' => 'require',
            'password' => 'require',
        ], [
            'username' => '账号不能为空',
            'password' => '密码不能为空',
        ]);
        if (!$validate->check($data)) {
            $msg['msg'] = $validate->getError();
            return $this->errorJson($msg);
        }
        //获取账号信息
        $account = Db::name('account')->where('account_name',$data['username'])->find();
        //判断账号和密码是否正确
        if(!$account || $account['password']!==md5($data['password'])){
            $msg['msg'] = '账号或密码不正确';
            return $this->errorJson($msg);
        }
        //接口 - 获取商家信息
        $merchant_model_api = Config('model_api.merchant');
        $url = $merchant_model_api . "/merchant/login_info";
        $merchant = Curl::get($url, array('account_id' => $account['id']));
        $merchant_status = Curl::json2arr($merchant)['status'];
        //判断账号是否存在
        if (!$merchant_status) {
            $msg['msg'] = '该账号无商家权限';
            return $this->errorJson($msg);
        }
        //取data重新赋值
        $merchant = Curl::json2arr($merchant)['data'];
        //商家账号状态判断
        if ($merchant['auditStatus'] == 'N'||$merchant['auditStatus'] == 'A') {
            $msg['msg'] = '账号已被禁用或者正在审核';
            return $this->errorJson($msg);
        }

        //生成并保存token
        $token_str = save_token($account['id']);
        //登录成功
        $msg['msg'] = '登录成功';
        $msg['token'] = $token_str;
        return $this->successJson($msg);
    }
    /**
     * @title 用户登录
     * @description 用户登录
     * @author 宋晓文
     * @url /login/login/user_login
     * @method POST
     * @param name:username type:int require:1 default:1 other: desc:账号
     * @param name:password type:int require:1 default:1 other: desc:密码
     * @return data:帐号信息@!
     * @data token:token
     *
     */
    public function user_login()
    {
        $data = input();
        //验证器
        $validate = new Validate([
            'username' => 'require',
            'password' => 'require',
        ], [
            'username' => '账号不能为空',
            'password' => '密码不能为空',
        ]);
        if (!$validate->check($data)) {
            $msg['msg'] = $validate->getError();
            return $this->errorJson($msg);
        }
        //获取账号信息
        $account = Db::name('account')->where('account_name',$data['username'])->find();
        //判断账号和密码是否正确
        if(!$account || $account['password']!==md5($data['password'])){
            $msg['msg'] = '账号或密码不正确';
            return $this->errorJson($msg);
        }
        //接口 - 获取用户数据
        $user_model_api = Config('model_api.user');
        $url = $user_model_api . "/user/info";
        $user = Curl::get($url, array('account_id' => $account['id']));
        $user_status = Curl::json2arr($user)['status'];
        //判断账号是否存在
        if (!$user_status) {
            $msg['msg'] = '该账号未注册用户';
            return $this->errorJson($msg);
        }
        //取data重新赋值
        $user = Curl::json2arr($user)['data'];
        //判断是否被禁用
        if ($user['status'] == 0) {
            $msg['msg'] = '该账号用户已被禁用';
            return $this->errorJson($msg);
        }

        //生成并保存token
        $token_str = save_token($account['id']);
        //登录成功
        $msg['msg'] = '登录成功';
        $msg['token'] = $token_str;
        return $this->successJson($msg);
    }

    /**
     * @title 小程序注册
     * @description 接口说明(flag登录标志.0:授权失败;1:注册成功;2已注册)
     * @author 刘春明
     * @desc 修改：宋晓文
     * @url /login/login/mini_register
     * @method ~
     * @param name:code type:string require:1
     * @param name:encryptedData type:string require:1
     * @param name:iv type:string require:1
     */
    public function mini_register()
    {
        $_data = input();
        $validate = new Validate([
            'code' => 'require',
            'encryptedData' => 'require',
            'iv' => 'require',
        ]);
        if (!$validate->check($_data)) {
            $msg['msg'] = $validate->getError();
            return $this->errorJson($msg);
        }
        //加载配置文件
        $config = Config("wechat.mini_program.default");
        //实例化小程序类
        $app = Factory::miniProgram($config);
        //获取微信用户openid和session_key
        $user_info = $app->auth->session($_data['code']);
        //解析用户信息
        $decryptedData = $app->encryptor->decryptData($user_info['session_key'], $_data['iv'], $_data['encryptedData']);

        logs('user_info', $user_info);
        logs('decryptedData', $decryptedData);
        if ($user_info) {
            $wx_user = account($user_info['openid']);
            if ($wx_user) {
                $msg['token'] = save_token($wx_user['id']);
                $msg['register'] = true;
                $msg['msg'] = "用户已注册";
                $msg['flag'] = 2;
                $msg['wx_user'] = $wx_user;
                return $this->successJson($msg);
            } else {
                $account['openId'] = $decryptedData['openId'];
                $account_id = Db::name('account')->insertGetId($account);
                if (!$account_id){
                    $msg['register'] = false;
                    $msg['token'] = false;
                    $msg['msg'] = "授权失败";
                    $msg['flag'] = 0;
                    return $this->errorJson($msg);
                }

                $wx_user['account_id'] = $account_id;
                $wx_user['nickName'] = $decryptedData['nickName'];      //昵称
                $wx_user['avatarUrl'] = $decryptedData['avatarUrl'];    //头像
                $wx_user['gender'] = $decryptedData['gender'];          //性别
                $wx_user['country'] = $decryptedData['country'];        //国家
                $wx_user['province'] = $decryptedData['province'];      //省份
                $wx_user['city'] = $decryptedData['city'];              //城市
                $wx_user['language'] = $decryptedData['language'];      //语言
                //添加数据到zb_user.tp_user中
                $res = get_curl('user', 'User/add_user', $wx_user);

                if ($res){
                    $msg['token'] = save_token($account_id);
                    $msg['register'] = true;
                    $msg['wx_user'] = $wx_user;
                    $msg['msg'] = "注册成功";
                    $msg['flag'] = 1;
                    return $this->successJson($msg);
                }else{
                    $msg['register'] = false;
                    $msg['token'] = false;
                    $msg['msg'] = "注册失败";
                    $msg['flag'] = 0;
                    return $this->errorJson($msg);
                }
            }
        } else {
            $msg['register'] = false;
            $msg['token'] = false;
            $msg['msg'] = "授权失败";
            $msg['flag'] = 0;
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 小程序登录
     * @description 接口说明(flag登录标志.0:用户未注册;1:登录成功并返回token;2登录成功但没有token)
     * @author 刘春明
     * @url /login/login/mini_login
     * @method ~
     * @param name:code type:string require:1
     */
    public function mini_login()
    {
        $_data = input();
        $validate = new Validate([
            'code' => 'require',
        ]);
        if (!$validate->check($_data)) {
            $msg['msg'] = $validate->getError();
            return $this->errorJson($msg);
        }
        //加载配置文件
        $config = Config("wechat.mini_program.default");

        //实例化小程序类
        $app = Factory::miniProgram($config);

        //获取微信用户信息
        $Session = $app->auth->session($_data['code']);
        if (!isset($Session['errcode'])) {
            $wx_user = account($Session['openid']);
            if (!$wx_user) {
                $msg['token'] = false;
                $msg['register'] = false;
                $msg['msg'] = "用户未注册";
                $msg['flag'] = 0;
                return $this->errorJson($msg);
            }

            $msg['wx_user'] = $wx_user;
            $msg['token'] = save_token($wx_user['account_id']);
            if (empty($msg['token'])) {
                $msg['flag'] = 2;
            } else {
                $msg['flag'] = 1;
            }
            $msg['msg'] = "登录成功";
            return $this->successJson($msg);
        } else {
            $msg['token'] = false;
            $msg['msg'] = "登录失败";
            $msg['session'] = $Session;
            return $this->errorJson($msg);
        }
    }

}
